<template>
  <div class="flx">
    <Card style="width: 100%;">
      <Tabs value="name1" @on-click="tabsOnClick">
        <TabPane label="用户列表" name="name1">
<!--          <Row>-->
<!--            <Form inline>-->
<!--              <FormItem>-->
<!--                <Input v-model="selectObj.login_name" clearable placeholder="登录名"/>-->
<!--              </FormItem>-->
<!--              <FormItem>-->
<!--                <Input v-model="selectObj.mobile" clearable placeholder="手机号"/>-->
<!--              </FormItem>-->
<!--              <FormItem>-->
<!--                <Button type="primary" @click="init()">搜索</Button>-->
<!--              </FormItem>-->
<!--            </Form>-->
<!--          </Row>-->
          <Table border :loading="tableLoading" :columns="columns" :data="data">
            <template slot-scope="{ row }" slot="action">
              <Button type="primary" size="small" v-if="row.del_flag === '0'" style="margin-right: 5px" @click="editRoleGroup(row)">设置权限</Button>
              <Button type="error" size="small" v-if="row.del_flag === '0'" style="margin-right: 5px" @click="showModal(row,'1')">密码重置</Button>
<!--              <Button type="error" size="small" v-if="row.del_flag === '0'" style="margin-right: 5px" @click="resetUser(row)">密码重置</Button>-->
              <Button type="warning" size="small" v-if="row.del_flag === '0'" style="margin-right: 5px" @click="showModal(row,'2')">作废</Button>
<!--              <Button type="warning" size="small" v-if="row.del_flag === '0'" @click="cancellation(row)">作废</Button>-->
              <Button type="success" size="small" v-if="row.login_flag === '10'" @click="getAddUserForWorker(row)">创建账号</Button>
<!--              <Button type="warning" size="small">作废</Button>-->
<!--              <Button type="info" size="small" @click="gridJurisdiction(row)" v-if="row.del_flag === '0'">划分网格权限</Button>-->
            </template>
          </Table>
          <div class="page">
            <Page :total="totalnum" :current="currentPageNo" :page-size="currentPageSize"
                  @on-change="change"/>
          </div>
        </TabPane>
        <Drawer
          title="配置权限"
          v-model="configPower"
          width="720"
          :mask-closable="false"
        >
          <div class="drawer-body">
            <Card v-for="(item,index) in spanList" :key="index" style="margin-bottom: 1%">
              <p slot="title">{{item.limit_system_dict}}</p>
              <CheckboxGroup v-model="userRoleGroupList">
                <Checkbox v-for="(item,index) in item.roleList"  :key="index" :label="item.id" border size="large" style="margin-bottom: 1%">{{item.name}}</Checkbox>
              </CheckboxGroup>
            </Card>
          </div>
          <div class="drawer-footer">
            <Button style="margin-right: 8px" @click="configPower = false">取消</Button>
            <Button type="primary" @click="editRoleGroupOk">保存</Button>
          </div>
        </Drawer>
<!--        <TabPane label="用户添加" name="name2">-->
<!--          <div class="user-form">-->
<!--            <Form ref="formInline" :model="userObj" :label-width="90">-->
<!--              <FormItem label="身份证号：">-->
<!--                <Input v-model="userObj.cardno" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="手机号码：">-->
<!--                <Input v-model="userObj.mobile" placeholder="手机号码" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="姓名：">-->
<!--                <Input v-model="userObj.name" placeholder="姓名" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="密码：">-->
<!--                <Input v-model="userObj.password" maxlength="20" type="password" placeholder="密码" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="确认密码：">-->
<!--                <Input v-model="userObj.passwordc" maxlength="20" type="password" placeholder="确认密码" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="邮箱：">-->
<!--                <Input v-model="userObj.email" placeholder="邮箱" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="电话：">-->
<!--                <Input v-model="userObj.phone" placeholder="电话" class="wid"></Input>-->
<!--              </FormItem>-->
<!--&lt;!&ndash;              <FormItem label="允许登录：">&ndash;&gt;-->
<!--&lt;!&ndash;                <i-switch v-model="userObj.login_flag" size="large">&ndash;&gt;-->
<!--&lt;!&ndash;                  <span slot="1">On</span>&ndash;&gt;-->
<!--&lt;!&ndash;                  <span slot="0">Off</span>&ndash;&gt;-->
<!--&lt;!&ndash;                </i-switch>&ndash;&gt;-->
<!--&lt;!&ndash;              </FormItem>&ndash;&gt;-->
<!--&lt;!&ndash;              <FormItem label="用户类型：">&ndash;&gt;-->
<!--&lt;!&ndash;                <Select v-model="userObj.user_type" class="wid">&ndash;&gt;-->
<!--&lt;!&ndash;                  <Option value="1">系统管理</Option>&ndash;&gt;-->
<!--&lt;!&ndash;                  <Option value="2">部门经理</Option>&ndash;&gt;-->
<!--&lt;!&ndash;                  <Option value="3">普通用户</Option>&ndash;&gt;-->
<!--&lt;!&ndash;                  <Option value="9">接口对接</Option>&ndash;&gt;-->
<!--&lt;!&ndash;                </Select>&ndash;&gt;-->
<!--&lt;!&ndash;              </FormItem>&ndash;&gt;-->
<!--              <FormItem label="用户角色组：">-->
<!--                <Card v-for="(item,index) in spanList" :key="index" style="margin-bottom: 1%" class="wid">-->
<!--                  <p slot="title">{{item.limit_system_dict}}</p>-->
<!--                  <CheckboxGroup v-model="userObj.groupList">-->
<!--                    <Checkbox v-for="(item,index) in item.roleList"  :key="index" :label="JSON.stringify(item)" border  style="margin-bottom: 1%">{{item.name}}</Checkbox>-->
<!--                  </CheckboxGroup>-->
<!--                </Card>-->
<!--              </FormItem>-->
<!--              <FormItem label="备注：">-->
<!--                <Input v-model="userObj.remarks" type="textarea" class="wid" placeholder=""/>-->
<!--              </FormItem>-->
<!--            </Form>-->
<!--            <div align="right">-->
<!--              <Button class="clic" type="primary" shape="circle" @click="addUser">添加</Button>-->
<!--              <Button class="ml20" shape="circle" >取消</Button>-->
<!--            </div>-->
<!--          </div>-->
<!--        </TabPane>-->
<!--        <TabPane label="用户修改"  name="name3">-->
<!--          <div class="user-form">-->
<!--            <Form ref="formInline" :model="obj" :label-width="90">-->
<!--              <FormItem label="归属地：">-->
<!--                <Input v-model="obj.company_name" :placeholder="this.obj.company_name" disabled-->
<!--                       class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="登录手机：">-->
<!--                <Input v-model="obj.mobile" placeholder="登录手机号" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="登录名：">-->
<!--                <Input v-model="obj.login_name" placeholder="登录名" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="工号：">-->
<!--                <Input v-model="obj.no" maxlength="20" placeholder="工号" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="姓名：">-->
<!--                <Input v-model="obj.name" placeholder="姓名" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="密码：">-->
<!--                <Input v-model="obj.password" maxlength="20" type="password" placeholder="密码"-->
<!--                       class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="确认密码：">-->
<!--                <Input v-model="obj.passwordc" maxlength="20" type="password" placeholder="确认密码"-->
<!--                       class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="邮箱：">-->
<!--                <Input v-model="obj.email" placeholder="邮箱" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="电话：">-->
<!--                <Input v-model="obj.phone" placeholder="电话" class="wid"></Input>-->
<!--              </FormItem>-->
<!--              <FormItem label="允许登录：">-->
<!--                <i-switch v-model="obj.login_flag" true-value="1" false-value="0" size="large">-->
<!--                  <span slot="1">On</span>-->
<!--                  <span slot="0">Off</span>-->
<!--                </i-switch>-->
<!--              </FormItem>-->
<!--              <FormItem label="用户类型：">-->
<!--                <Select v-model="obj.user_type" class="wid">-->
<!--                  <Option value="1">系统管理</Option>-->
<!--                  <Option value="2">部门经理</Option>-->
<!--                  <Option value="3">普通用户</Option>-->
<!--                  <Option value="9">接口对接</Option>-->
<!--                </Select>-->
<!--              </FormItem>-->
<!--              <FormItem label="用户角色：">-->
<!--                <Card v-for="(item,index) in spanList" :key="index" style="margin-bottom: 1%" class="wid">-->
<!--                  <p slot="title">{{item.limit_system}}</p>-->
<!--                  <CheckboxGroup >-->
<!--                    <Checkbox v-for="(item,index) in item.roleList"  :key="index" :label="item.id" border  style="margin-bottom: 1%">{{item.name}}</Checkbox>-->
<!--                  </CheckboxGroup>-->
<!--                </Card>-->
<!--              </FormItem>-->
<!--              <FormItem label="备注：">-->
<!--                <Input v-model="obj.remarks" type="textarea" class="wid" placeholder=""/>-->
<!--              </FormItem>-->
<!--              <FormItem label="备注：">-->
<!--                <span class="lef">时间：{{obj.update_date}}</span>-->
<!--              </FormItem>-->
<!--            </Form>-->
<!--            <div>-->
<!--              <Button class="clic" type="primary" shape="circle" >保存</Button>-->
<!--              <Button class="ml20" shape="circle">取消</Button>-->
<!--            </div>-->
<!--          </div>-->
<!--        </TabPane>-->
      </Tabs>
    </Card>
    <Modal
      v-model="gridJurisdictionModal"
      title="划分网格系统权限"
      width="500"
      @on-ok="gridJurisdictionOk">
        <Tag style="margin-right: 10px" color="primary">当前勾选表示拥有权限！</Tag>
        <Button style="margin-right: 10px" @click="gridJurisdictionForButton(true)">展开</Button>
        <Button @click="gridJurisdictionForButton(false)">关闭</Button>
        <div style="overflow-y: auto;height: 400px">
          <Tree :data="treeData" show-checkbox ref="GridTree"></Tree>
        </div>
    </Modal>
    <Modal
      v-model="commonModal.show"
      :title="commonModal.title">
      <p style="font-size: 1.6rem">{{commonModal.body}}</p>
      <div slot="footer">
        <Button type="text"  @click="commonModal.show = false">取消</Button>
        <Button type="primary" v-if="commonModal.type === '1'" @click="resetUser(rowData)">确认</Button>
        <Button type="primary" v-if="commonModal.type === '2'" @click="cancellation(rowData)">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getUserList, getRoleGroupList, getAddUser, getUserRoleGroupList, getEditUserRoleGroup, getUpdateResetAccount, updateUser, getAddUserForWorker } from '@/api/eventlist'
import { DivideJurisdiction, findCommunityGridList } from '../../../api/eventlist'

export default {
  data () {
    return {
      treeData: [],
      gridJurisdictionInfo: {},
      gridJurisdictionModal: false,
      commonModal: {
        show: false,
        title: '',
        body: '',
        type: ''
      },
      row: {},
      rowData: {},
      userRoleGroupList: [],
      groupList: [],
      userObj: {},
      tableLoading: false,
      configPower: false,
      btnlist: [],
      spanList: [],
      obj: {},
      data: [],
      columns: [
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h('div', [
              h('Table', {
                props: {
                  columns: [
                    {
                      title: '历史账号信息',
                      key: 'login_name',
                      align: 'center',
                      width: 100,
                      children: [
                        {
                          title: '归属地',
                          key: 'company_name',
                          align: 'center'
                        },
                        {
                          title: '登录名',
                          key: 'login_name',
                          align: 'center'
                        },
                        { title: '姓名',
                          key: 'name',
                          align: 'center',
                          width: 100
                        },
                        {
                          title: '手机号',
                          key: 'mobile',
                          align: 'center'
                        },
                        {
                          title: '停用时间',
                          key: 'stop_time',
                          align: 'center'
                        }
                      ]
                      // render: (h, params) => {
                      //   let text = `${
                      //     params.row.login_name
                      //   }`
                      //   return h(
                      //     'div',
                      //     {
                      //       style: {
                      //         overflow: 'hidden',
                      //         whiteSpace: 'nowrap',
                      //         textOverflow: 'ellipsis',
                      //         'text-align': 'center'
                      //       },
                      //       attrs: {
                      //         title: text
                      //       }
                      //     },
                      //     text
                      //   )
                      // }
                    }
                  ],
                  'show-header': true,
                  data: params.row.historyList }
              })
            ])
          }
        },
        {
          title: '社区工作者实名制登记系统',
          align: 'center',
          children: [
            {
              title: '归属地',
              key: 'company_name',
              align: 'center'
            },
            { title: '姓名',
              key: 'name',
              align: 'center',
              width: 100
            },
            { title: '身份证号',
              key: 'cardno',
              align: 'center'
            },
            {
              title: '手机号',
              key: 'phone',
              align: 'center'
            },
            {
              title: '职务',
              key: 'zw',
              align: 'center'
            }
          ]
        },
        {
          title: '基层治理服务管理平台',
          align: 'center',
          children: [
            {
              title: '登录名',
              key: 'login_name',
              align: 'center'
            },
            {
              title: '账号状态',
              key: 'login_flag_mean',
              align: 'center'
            }
          ]
        },
        {
          title: '操作',
          slot: 'action',
          width: 350,
          align: 'center'
        }
      ],
      currentPageNo: 1,
      currentPageSize: 20,
      totalnum: 0,
      selectObj: {}
    }
  },
  mounted () {
    this.init()
    this.initGroupList()
  },
  methods: {
    gridJurisdiction (row) {
      console.log(row)
      let data = {
        login_name: row.login_name
      }
      findCommunityGridList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.gridJurisdictionInfo = row
          this.gridJurisdictionModal = true
          this.treeData = ret.data.data
        } else {
          this.$Notice.error({ title: '失败', desc: ret.data.errmsg })
        }
      })
    },
    gridJurisdictionForButton (expand) {
      let data = {
        login_name: this.gridJurisdictionInfo.login_name,
        expand: expand
      }
      findCommunityGridList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.treeData = ret.data.data
        } else {
          this.$Notice.error({ title: '失败', desc: ret.data.errmsg })
        }
      })
    },
    gridJurisdictionOk () {
      let data = {
        login_name: this.gridJurisdictionInfo.login_name,
        checkNodes: this.$refs.GridTree.getCheckedNodes()
      }
      console.log(data)
      DivideJurisdiction(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({ title: '保存成功', desc: ret.data.errmsg })
        } else {
          this.$Notice.error({ title: '保存失败', desc: ret.data.errmsg })
        }
      })
    },
    showModal (row, type) {
      this.rowData = row
      if (type === '1') {
        this.commonModal.title = '密码重置'
        this.commonModal.body = '确定重置该账号的密码为：qstb@2020该操作不可恢复，请谨慎使用！'
        this.commonModal.type = type
      }
      if (type === '2') {
        this.commonModal.title = '作废账号'
        this.commonModal.body = '确定作废此账号吗?该操作不可恢复，请谨慎使用！'
        this.commonModal.type = type
      }
      this.commonModal.show = true
    },
    init () {
      let params = {
        loginname: this.selectObj.login_name,
        mobile: this.selectObj.mobile,
        pageSize: this.currentPageSize,
        pageNo: this.currentPageNo
      }
      this.tableLoading = true
      getUserList(params).then(ret => {
        if (ret.data.errcode === 0) {
          this.data = ret.data.data.results
          this.data.forEach(function (temp) {
            if (temp.login_flag === '1') {
              temp.login_flag_mean = '正常登录'
            } else if (temp.login_flag === '0') {
              temp.login_flag_mean = '不可登录'
            } else if (temp.login_flag === '10') {
              temp.login_flag_mean = '无账号'
            }
            // if (temp.del_flag === '1') {
            //   temp.login_flag_mean = '已作废'
            // }
          })
          console.log(this.data)
          this.totalnum = ret.data.data.totalRecord
          this.tableLoading = false
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    initGroupList () {
      console.log('111')
      getRoleGroupList().then(ret => {
        if (ret.data.errcode === 0) {
          this.spanList = ret.data.data
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    tabsOnClick (name) {
      console.log(name)
      switch (name) {
        case 'name2':
          this.initGroupList()
          break
        default:
          break
      }
    },
    addUser () {
      console.log(this.userObj)
      if (this.userObj.cardno === null || this.userObj.cardno === '' || this.userObj.cardno === undefined) {
        this.$Message.info('请填写身份证号码！')
        return
      }
      var regCard = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
      if (regCard.test(this.userObj.cardno) === false) {
        this.$Message.info('请输入正确身份证号！')
        this.userObj.cardno = ''
        return
      }
      if (this.userObj.mobile === null || this.userObj.mobile === '' || this.userObj.mobile === undefined) {
        this.$Message.info('请填写手机号码！')
        return
      }
      var reg = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
      if (reg.test(this.userObj.mobile) === false) {
        this.$Message.info('请输入正确手机号！')
        this.userObj.mobile = ''
        return
      }
      if (this.userObj.name === null || this.userObj.name === '' || this.userObj.name === undefined) {
        this.$Message.info('请填写姓名！')
        return
      }
      if (this.userObj.password === null || this.userObj.password === '' || this.userObj.password === undefined) {
        this.$Message.info('请填写密码！')
        return
      }
      if (this.userObj.passwordc === null || this.userObj.passwordc === '' || this.userObj.passwordc === undefined) {
        this.$Message.info('请再次填写密码！')
        return
      }
      if (this.userObj.passwordc !== this.userObj.password) {
        this.$Message.info('两次密码不相同！')
        return
      }
      let limit_system = ''
      let groupList = []
      if (this.userObj.groupList) {
        let nameList = []
        this.userObj.groupList.forEach(function (temp, index) {
          let obj = JSON.parse(temp)
          nameList.push(obj.limit_system)
          groupList.push(obj.id)
        })
        let getProtocalNum = new Set(nameList)
        let getProtocalNumArr = Array.from(getProtocalNum)
        limit_system = getProtocalNumArr.join(',')
      }
      let params = {
        cardno: this.userObj.cardno,
        email: this.userObj.email,
        mobile: this.userObj.mobile,
        name: this.userObj.name,
        password: this.userObj.password,
        passwordc: this.userObj.passwordc,
        phone: this.userObj.phone,
        remarks: this.userObj.remarks,
        groupList: groupList,
        limit_system: limit_system + ','
      }
      getAddUser(params).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: ret.data.data.message,
            desc: '账号为:' + ret.data.data.login_name,
            duration: 0
          })
          this.init()
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    getAddUserForWorker (row) {
      getAddUserForWorker(row).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: ret.data.data.message,
            desc: '账号为:' + ret.data.data.login_name + '\n' + '密码为:' + ret.data.data.password,
            duration: 0
          })
          this.init()
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    editRoleGroup (row) {
      this.row = row
      getUserRoleGroupList(row).then(ret => {
        if (ret.data.errcode === 0) {
          this.userRoleGroupList = ret.data.data
          this.configPower = true
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    editRoleGroupOk () {
      if (this.userRoleGroupList.length === 0) {
        if (!confirm('未选择任何角色组,将会删除该用户所有角色组！该操作不可恢复，请谨慎使用！')) {
          return
        }
      }
      let params = {
        user_id: this.row.id,
        groupList: this.userRoleGroupList
      }
      getEditUserRoleGroup(params).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '修改成功',
            desc: ret.data.data.message
          })
          this.configPower = false
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    cancellation (row) {
      updateUser(row).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '作废成功',
            desc: ret.data.data.message
          })
          this.configPower = false
          this.init()
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    resetUser (row) {
      console.log(row)
      getUpdateResetAccount(row).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '重置成功',
            desc: ret.data.data.message
          })
          this.init()
          this.configPower = false
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    //  分页
    change (pageNo) {
      this.currentPageNo = pageNo
      this.currentPageSize = 20
    }
  },
  watch: {}
}
</script>

<style scoped>
.user-form {
  width: 70%;
  margin: 0 auto;
}
.flx {
  display: flex;
}
.wid {
  width: 90%;
}
.page {
  margin-top: 10px;
  text-align: right;
}
.drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.drawer-body {
  height: 90%;
  overflow: auto;
}

</style>
